package com.hx.thread.future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * @author Minghua Chen
 * @date 2020-09-05 19:04
 */
public class FutureDemo {
    private static final Logger logger = LoggerFactory.getLogger(FutureDemo.class);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        ArrayList<Future<String>> futureList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Future<String> future;
            if (i == 0 || i == 1) {
                future = executorService.submit(new SlowTask());
            } else {
                future = executorService.submit(new FastTask());
            }
            futureList.add(future);
        }
        for (int i = 0; i < 4; i++) {
            Future<String> future = futureList.get(i);
            try {
                String result = future.get();
                logger.info(result);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        executorService.shutdown();
    }

    static class SlowTask implements Callable<String> {
        @Override
        public String call() throws Exception {
            Thread.sleep(5000);
            return "速度慢的任务";
        }
    }

    static class FastTask implements Callable<String> {
        @Override
        public String call() throws Exception {
            return "速度快的任务";
        }
    }
}

